﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;

namespace Zeus.Components.Nopi.Excel
{
    public class GenericExcelFormater<T>
    {
        public static void WriteSingleTable(HSSFWorkbook workBook, Sheet sheet, ref int rowNum, int colNum,
            List<T> bodyList, Dictionary<string, string> headDict, TemplateSetting templateSetting)
        {
            WorkBookModel headModel = WorkBookInitializer.GetInitModel(workBook);
            WorkBookModel bodyModel = WorkBookInitializer.GetInitModel(workBook);

            int colInc = 0;
            Row row;
            Cell cell;

            // create header
            rowNum++;
            row = sheet.CreateRow(rowNum);
            foreach (KeyValuePair<string, string> headElem in headDict)
            {
                cell = row.CreateCell(colNum + colInc);
                cell.SetCellValue(headElem.Value);

                ExcelFormatHelper.FormatTableHead(cell, headModel.CellStyle, headModel.Font, headModel.Palette, templateSetting);

                colInc++;
            }

            // create body
            colInc = 0;
            string cellValue = string.Empty;
            foreach (T bodyElem in bodyList)
            {
                rowNum++;
                row = sheet.CreateRow(rowNum);

                colInc = 0;
                Type type = bodyElem.GetType();
                foreach (KeyValuePair<string, string> headElem in headDict)
                {
                    PropertyInfo propertyInfo = type.GetProperty(headElem.Key);
                    cellValue = propertyInfo.GetValue(bodyElem, null).ToString();

                    // set cell value
                    cell = row.CreateCell(colNum + colInc);
                    cell.SetCellValue(cellValue);

                    ExcelFormatHelper.FormatTableBody(cell, bodyModel.CellStyle, bodyModel.Font, bodyModel.Palette, templateSetting);

                    colInc++;
                }
            }
        }
    }
}
